<template>
  <div :style="{ height: height, width: width }"></div>
</template>

<script>
import resize from "./mixins/resize";
export default {
  name: "echart", // 通用的echart组件
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    chartOption: {
      type: Object,
      default() {
        return {
          title: {
            text: "世界人口总量",
            left: "center"
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow"
            }
          },
          grid: {
            left: "1%",
            right: "4%",
            bottom: "3%",
            containLabel: true
          },
          xAxis: {
            type: "value",
            boundaryGap: [0, 0.01]
          },
          yAxis: {
            type: "category",
            data: ["巴西", "印尼", "美国", "印度", "中国", "世界人口(万)"]
          },
          series: [
            {
              name: "2011年",
              type: "bar",
              data: [18203, 23489, 29034, 104970, 131744, 630230]
            },
            {
              name: "2012年",
              type: "bar",
              data: [19325, 23438, 31000, 121594, 134141, 681807]
            }
          ]
        };
      }
    }
  },
  watch: {
    chartOption: {
      deep: true,
      handler(val) {
        if (this.chart) {
          this.setOption(val);
        } else {
          this.initChart();
        }
      }
    }
  },
  data() {
    return {
      chart: null
    };
  },
  methods: {
    /**
     * 初始化图表实例
     */
    initChart() {
      this.chart = this.$echarts.init(this.$el, "macarons");
      this._setOption(this.chartOption || {});
    },

    /**
     * 设置图标的option
     * @param {Object} option
     */
    _setOption(option = this.chartOption) {
      this.chart.setOption(option, true);
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) return;
    this.chart.dispose();
    this.chart = null;
  }
};
</script>

<style scoped></style>
